package com.yh.service.impl;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.yh.domain.User;
import com.yh.service.IExcelService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 导入导出excel Hutool
 *
 * @author yh
 * @date 2021-4-4
 */
@Service
@Log4j2
public class ExcelServiceImpl implements IExcelService {

    @Override
    public List<User> exportExcel() {
        List<User> users = new ArrayList<>();
        users.add(User.builder().id("1").nickName("张三").phone("18222222222").age(20).sex("男").build());
        users.add(User.builder().id("2").nickName("李四").phone("18222222222").age(20).sex("男").build());
        users.add(User.builder().id("3").nickName("王五").phone("18222222222").age(20).sex("男").build());
        users.add(User.builder().id("4").nickName("陈六").phone("18222222222").age(20).sex("男").build());
        users.add(User.builder().id("5").nickName("余七").phone("18222222222").age(20).sex("男").build());
        users.add(User.builder().id("6").nickName("杨八").phone("18222222222").age(20).sex("男").build());
        return users;
    }

    @Override
    public void importExcel(MultipartFile file) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (Exception e) {
            log.info(e);
        }
        ExcelReader excelReader = ExcelUtil.getReader(inputStream);
        List<Map<String, Object>> users = excelReader.readAll();
        if(StringUtils.isEmpty(users) || users.size() < 1){
            return;
        }
        for(Map<String, Object> map : users){
            System.out.print(map.get("id"));
            System.out.print(map.get("nickName"));
            System.out.print(map.get("phone"));
            System.out.print(map.get("age"));
            System.out.println(map.get("sex"));
        }
    }
}
